package com.enki.cigarettes.controller;

import com.enki.cigarettes.controller.vo.request.CommentRequestVo;
import com.enki.cigarettes.controller.vo.response.ProductCommentResponseVo;
import com.enki.cigarettes.entity.*;
import com.enki.cigarettes.enums.CommentEnums;
import com.enki.cigarettes.enums.ProductEnums;
import com.enki.cigarettes.handler.Response;
import com.enki.cigarettes.repository.*;
import com.enki.cigarettes.statics.StaticKeys;
import com.enki.cigarettes.utils.DateUtils;
import com.enki.cigarettes.utils.PrimaryKey;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author WCS.Wang
 * @version V1.0
 * @Package com.enki.cigarettes.controller
 * @Name e-cigarettes-shop-api-module
 * @Description: TODO 商品评论
 * @date 2019-07-21
 */
@RestController
@RequestMapping("/api/product/comments")
@Slf4j
public class ProductCommentController {

    @Autowired
    ProductCommentTRepository productCommentTRepository;
    @Autowired
    ProductCommentPictureTRepository productCommentPictureTRepository;
    @Autowired
    OrderTRepository orderTRepository;
    @Autowired
    OrderItemTRepository orderItemTRepository;
    @Autowired
    UserTRepository userTRepository;
    @Autowired
    ProductSkuTRepository productSkuTRepository;
    @Autowired
    CategoryAttrTRepository categoryAttrTRepository;
    @Autowired
    CategoryAttrValTRepository categoryAttrValTRepository;
    @Autowired
    TradeSnapshotTRepository tradeSnapshotTRepository;


    @ApiOperation(value = "商品评论列表")
    @GetMapping(value = "/{id}")
    public Object findByOrderId(@PathVariable String id, HttpSession session) {
        try {
            Object sessionId = session.getAttribute(StaticKeys.USER_ID);
            if (sessionId == null) {
                return Response.unauthorized_401("登录身份失效，请重新登录");
            }
            Map<String, Object> responseData = new HashMap<>();
            OrderT order = orderTRepository.findOneByIdAndUserTIdAndRemoved(id, sessionId.toString(), StaticKeys.REMOVED);
            if (order == null) {
                return Response.notFound_404("不存在的订单信息，请核实");
            }
            // 订单类目
            List<OrderItemT> orderItemList = orderItemTRepository.findByOrderTId(order.getId());
            List<ProductCommentResponseVo> items = new ArrayList<>();
            if (order.getCommentStatus() == CommentEnums.CommentStatus.PENDING.getStatus()) {
                for (OrderItemT orderItem : orderItemList) {
                    TradeSnapshotT tradeSnapshot = tradeSnapshotTRepository.findByOrderTIdAndOrderItemTId(order.getId(), orderItem.getId());
                    if (tradeSnapshot != null) {
                        ProductCommentResponseVo item = new ProductCommentResponseVo();
                        item.setOrderItemId(orderItem.getId());
                        item.setName(tradeSnapshot.getName());
                        item.setSkuPicture(tradeSnapshot.getSkuPicture());
                        item.setProductPrice(orderItem.getProductPrice());
                        item.setQuantity(orderItem.getQuantity());
                        item.setProductSkuName(orderItem.getProductSkuName());
                        items.add(item);
                    }
                }
            } else {
                for (OrderItemT orderItem : orderItemList) {
                    TradeSnapshotT tradeSnapshot = tradeSnapshotTRepository.findByOrderTIdAndOrderItemTId(order.getId(), orderItem.getId());
                    if (tradeSnapshot != null) {
                        ProductCommentResponseVo item = new ProductCommentResponseVo();
                        item.setOrderItemId(orderItem.getId());
                        item.setName(tradeSnapshot.getName());
                        item.setSkuPicture(tradeSnapshot.getSkuPicture());
                        item.setProductPrice(orderItem.getProductPrice());
                        item.setQuantity(orderItem.getQuantity());
                        item.setProductSkuName(orderItem.getProductSkuName());
                        ProductCommentT productComment = productCommentTRepository.findOneByOrderTIdAndOrderItemTIdAndProductTIdAndProductSkuTId(orderItem.getOrderTId(), orderItem.getId(), orderItem.getProductTId(), orderItem.getProductSkuTId());
                        if (productComment != null) {
                            item.setComment(productComment.getComment());
                            item.setScore(productComment.getScore());
                            item.setReplyComment(productComment.getReplyComment());
                            item.setReplyScore(productComment.getReplyScore());
                            item.setReplyStatus(productComment.isReplyStatus());
                            List<ProductCommentPictureT> pictureList = productCommentPictureTRepository.findByProductCommentTId(productComment.getId());
                            item.setPictureItems(pictureList);
                        }
                        items.add(item);
                    }
                }
            }
            responseData.put("orderId", order.getId());
            responseData.put("createTime", DateUtils.getDateYMDHMS(order.getCreateTime()));
            responseData.put("commentStatus", order.getCommentStatus());
            responseData.put("orderItems", items);
            return Response.success(responseData, StaticKeys.SUCCESS);
        } catch (Exception e) {
            log.error("获取商品评论列表失败：" + e.getMessage());
            e.printStackTrace();
            return Response.serverError_500("服务器错误，获取商品评论列表失败");
        }
    }

    @ApiOperation(value = "保存评论信息")
    @ApiImplicitParam(name = "id", value = "订单ID", dataType = "String", required = true)
    @PostMapping(value = "/{id}")
    @Transactional
    public Object saveProductComment(@PathVariable String id, @RequestBody CommentRequestVo[] items, HttpSession session) {
        try {
            Object sessionId = session.getAttribute(StaticKeys.USER_ID);
            if (sessionId == null) {
                return Response.unauthorized_401("登录身份失效，请重新登录");
            }
            OrderT order = orderTRepository.findOneByIdAndUserTIdAndRemoved(id, sessionId.toString(), StaticKeys.REMOVED);
            if (order == null) {
                return Response.notFound_404("不存在的订单信息，请核实");
            }
            List<ProductCommentT> commentItems = new ArrayList<>();
            List<ProductCommentPictureT> pictureItems = new ArrayList<>();
            for (int i = 0; i < items.length; i++) {
                OrderItemT orderItem = orderItemTRepository.findOneById(items[i].getOrderItemId());
                if (orderItem != null) {
                    ProductCommentT commentItem = new ProductCommentT();
                    commentItem.setId(PrimaryKey.get().toString());
                    commentItem.setOrderTId(id);
                    commentItem.setOrderItemTId(orderItem.getId());
                    commentItem.setUserTId(sessionId.toString());
                    commentItem.setProductTId(orderItem.getProductTId());
                    commentItem.setProductSkuTId(orderItem.getProductSkuTId());
                    commentItem.setComment(items[i].getComment());
                    commentItem.setType(0);
                    commentItem.setScore(items[i].getScore());
                    commentItem.setZanCount(0);
                    commentItem.setReplyComment(StaticKeys.NULL);
                    commentItem.setReplyScore(0);
                    commentItem.setReplyStatus(false);
                    commentItem.setCreateTime(new Date());
                    commentItem.setUpdateTime(new Date());
                    commentItems.add(commentItem);
                    // 图片
//                    String[] images = items[i].getImages().split(StaticKeys);
                    for (String str : items[i].getImages()) {
                        ProductCommentPictureT pictureItem = new ProductCommentPictureT();
                        pictureItem.setId(PrimaryKey.get().toString());
                        pictureItem.setProductCommentTId(commentItem.getId());
                        pictureItem.setPictureUrl(str);
                        pictureItem.setCreateTime(new Date());
                        pictureItem.setUpdateTime(new Date());
                        pictureItems.add(pictureItem);
                    }
                }
            }
            productCommentTRepository.saveAll(commentItems);
            productCommentPictureTRepository.saveAll(pictureItems);
            order.setCommentStatus(CommentEnums.CommentStatus.COMMENT.getStatus());
            orderTRepository.save(order);
            return Response.success();
        } catch (Exception e) {
            log.error("保存商品评论失败：" + e.getMessage());
            e.printStackTrace();
            return Response.serverError_500("服务器错误，保存商品评论失败");
        }
    }

    @ApiOperation(value = "获取商品评论信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "商品ID", dataType = "long", required = true),
            @ApiImplicitParam(name = "page", value = "页码", required = true, dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页数据", required = true, dataType = "int")
    })
    @GetMapping(value = "/{id}/list")
    public Object findByProductIdAndPage(@PathVariable long id, @RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "20") int size) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Map<String, Object> responseData = new HashMap<>();
            Sort sort = new Sort(Sort.Direction.DESC, StaticKeys.SORT_CREATE_TIME);
            Pageable pageable = PageRequest.of(page, size, sort);
            Page<ProductCommentT> beanPage = productCommentTRepository.findByProductTId(id, pageable);
            List<ProductCommentResponseVo> vos = new ArrayList<>();
            for (ProductCommentT bean : beanPage.getContent()) {
                ProductCommentResponseVo vo = new ProductCommentResponseVo();
                vo.setId(bean.getId());
                UserT user = userTRepository.findOneById(bean.getUserTId());
                if (user != null) {
                    if (StringUtils.isNotBlank(user.getHeadPortrait())) {
                        vo.setHeadPortrait(user.getHeadPortrait());
                    }
                    vo.setNickname(user.getNickname());
                }
                vo.setComment(bean.getComment());
                vo.setScore(bean.getScore());
                ProductSkuT productSkuBean = productSkuTRepository.findFirstById(bean.getProductSkuTId());
                // 如果此商品sku不存在跳出当前循环
                if (productSkuBean == null) {
                    continue;
                }
                vo.setSku(productSkuBean.getProductSkuAttrValName());
//                String[] skuArr = productSkuBean.getSkuCode().split(StaticKeys.PRODUCT_SKU_SPLIT);
//                if (skuArr.length == 2) {
//                    CategoryAttrValT categoryAttrValBean = categoryAttrValTRepository.findOneById(skuArr[0]);
//                    if (categoryAttrValBean != null) {
//                        CategoryAttrT categoryAttrBean = categoryAttrTRepository.findOneById(categoryAttrValBean.getCategoryAttrTId());
//                        if (categoryAttrBean != null && categoryAttrBean.isIsColor()) {
//                            CategoryAttrValT sizeCategoryAttrBean = categoryAttrValTRepository.findOneById(skuArr[1]);
//                            if (sizeCategoryAttrBean != null) {
//                                vo.setSku(categoryAttrValBean.getName() + " " + sizeCategoryAttrBean.getName());
//                            }
//                        } else {
//                            CategoryAttrValT colorCategoryAttrBean = categoryAttrValTRepository.findOneById(skuArr[1]);
//                            if (colorCategoryAttrBean != null) {
//                                vo.setSku(colorCategoryAttrBean.getName() + " " + categoryAttrValBean.getName());
//                            }
//                        }
//                    }
//                } else if (skuArr.length == 1) {
//                    CategoryAttrValT categoryAttrBean = categoryAttrValTRepository.findOneById(skuArr[0]);
//                    if (categoryAttrBean != null) {
//                        vo.setSku(categoryAttrBean.getName());
//                    }
//                }
                vo.setCreateTime(sdf.format(bean.getCreateTime()));
                vo.setZanCount(bean.getZanCount());
                List<ProductCommentPictureT> pictureItems = productCommentPictureTRepository.findByProductCommentTId(bean.getId());
                vo.setPictureItems(pictureItems);
                vos.add(vo);
            }
            responseData.put("content", vos);
            responseData.put("number", beanPage.getNumber());
            responseData.put("totalPages", beanPage.getTotalPages());
            responseData.put("totalElements", beanPage.getTotalElements());
            responseData.put("size", beanPage.getSize());
            responseData.put("last", beanPage.isLast());
            return Response.success(responseData, StaticKeys.SUCCESS);
        } catch (Exception e) {
            log.error("获取商品评论失败：" + e.getMessage());
            e.printStackTrace();
            return Response.serverError_500("获取商品评论失败");
        }
    }


    @ApiOperation(value = "获取前5条 商品评论信息")
    @ApiImplicitParam(name = "id", value = "商品ID", dataType = "long", required = true)
    @GetMapping(value = "/{id}/top5")
    public Object findTop5ByProductId(@PathVariable long id) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Sort sort = new Sort(Sort.Direction.DESC, StaticKeys.SORT_CREATE_TIME);
            List<ProductCommentT> beanPage = productCommentTRepository.findTop5ByProductTId(id, sort);
            List<ProductCommentResponseVo> vos = new ArrayList<>();
            for (ProductCommentT bean : beanPage) {
                ProductCommentResponseVo vo = new ProductCommentResponseVo();
                vo.setId(bean.getId());
                UserT user = userTRepository.findOneById(bean.getUserTId());
                if (user != null) {
                    if (StringUtils.isNotBlank(user.getHeadPortrait())) {
                        vo.setHeadPortrait(user.getHeadPortrait());
                    }
                    vo.setNickname(user.getNickname());
                }
                vo.setComment(bean.getComment());
                vo.setScore(bean.getScore());
                ProductSkuT productSkuBean = productSkuTRepository.findFirstById(bean.getProductSkuTId());
                // 如果此商品sku不存在跳出当前循环
                if (productSkuBean == null) {
                    continue;
                }
                vo.setSku(productSkuBean.getProductSkuAttrValName());
                vo.setCreateTime(sdf.format(bean.getCreateTime()));
                vo.setZanCount(bean.getZanCount());
                List<ProductCommentPictureT> pictureItems = productCommentPictureTRepository.findByProductCommentTId(bean.getId());
                vo.setPictureItems(pictureItems);
                vos.add(vo);
            }
            return Response.success(vos, StaticKeys.SUCCESS);
        } catch (Exception e) {
            log.error("获取商品评论失败：" + e.getMessage());
            e.printStackTrace();
            return Response.serverError_500("获取商品评论失败");
        }
    }

}
